
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author dttung
 */
@WebServlet("/Edit")
public class Edit extends HttpServlet
{
    private HttpSession session;
    private final int nTours = 38;
    HashMap teaminput = new HashMap();
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException, FileNotFoundException
    {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();
        ServletUtil.printFistHalf(out);
        
        // check session and password
        if (!SessionVerify(request, response)) return;
        
        // session and pass correct
        Utils myUtil = new Utils();
        try {
            myUtil.readYffScores();
        } catch (URISyntaxException ex) {
            out.println(ex.getMessage());
        }
        int selectedWeek;//  
        int currWeek = myUtil.getCurrentRound(); // diem duoc cap nhat den day
        
        String week = request.getParameter("week");
        String checkSubmit = request.getParameter("selweek");
        
        if (week != null) // week is selected by drop down box
            selectedWeek = Integer.valueOf(week);            
        else if (checkSubmit != null)
            selectedWeek = Integer.valueOf(checkSubmit);            
        else
            selectedWeek = currWeek + 1; // first time entering
        
        printFormSelectWeek(out, selectedWeek);
        
        if (checkSubmit != null)
        {
            selectedWeek = Integer.valueOf(checkSubmit); // do 2 form khac nhau phai gui tu form update > select
            // update yff scores
            Iterator it = myUtil.yffscores.entrySet().iterator();            
            while (it.hasNext())
            {
                Map.Entry pairs = (Map.Entry)it.next();
                String team = (String) pairs.getKey();
                String score = request.getParameter(String.valueOf(teaminput.get(team)));
                myUtil.updateYffScore(team, score, selectedWeek); 
            }
            // then update whole table 
            // if selectedWeek <= currWeek => cap nhat den currWeek
            // if selectedWeek > currWeek => cap nhat den selectedWeek
            int weekToUpdate = 0;
            if (selectedWeek <= currWeek) weekToUpdate = currWeek;
            else weekToUpdate = selectedWeek;
            try {
                myUtil.initTeamScores();
                for (int w = 1; w <= weekToUpdate; w++) // update whole table to weekToUpdate
                {
                    ArrayList<String> lstmatches = new ArrayList<String>();
                    lstmatches = myUtil.getMatches(w);
                    myUtil.updateMatches(lstmatches, w);
                    myUtil.readTeamScores(); // update teamscore                    
                }
            } catch (Exception ex)
            {
                out.println(ex.getMessage());
            }
            // then save files
            try 
            {
                //myUtil.writeTeamScores();
                myUtil.writeYffScores();
            } catch (URISyntaxException ex) {
                out.println(ex.getMessage());
            }            
            
            //out.println("Đã cập nhật thành công!");
            //printFormUpdateTeams(out, myUtil, selectedWeek);
        }
        
        printFormUpdateTeams(out, myUtil, selectedWeek);
        
        
        ServletUtil.printSecondHalf(out);
    }
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        doGet(request, response);
    }
    private boolean SessionVerify(HttpServletRequest request,HttpServletResponse response) throws IOException
    {
        PrintWriter out = response.getWriter();
        session = request.getSession(false);
        if (session == null) // not login yet, no session stored
        {
            String pass = request.getParameter("pass");
            if (pass == null) // not login yet need to login now
            {
                out.println("<p><strong><font color=\"red\">Đăng nhập để truy cập trang này!</font></strong></p>");
                out.println("<form action=\"Edit\" method=\"POST\">\n" +
                            "Mật khẩu: <input type=\"password\" name=\"pass\">" +
                            "<input type=\"submit\" value=\"Submit\">" +
                            "</form>");
                ServletUtil.printSecondHalf(out);
                return false;
            } else if (!pass.equals("bunthitcho13"))
            {
                out.println("<p><strong><font color=\"red\">Sai mật khẩu!</font></strong></p>");
                out.println("<form action=\"Edit\" method=\"POST\">\n" +
                            "Mật khẩu: <input type=\"password\" name=\"pass\">" +
                            "<input type=\"submit\" value=\"Submit\">" +
                            "</form>");
                ServletUtil.printSecondHalf(out);
                return false;
            } else // pass is correct
            {
                // Create session
                session = request.getSession(true);
                session.setAttribute(pass, "bunthitcho13");
            }
        }
        return true;
    }

    private void printFormSelectWeek(PrintWriter out, int selIndex)
    {
        out.println("<form action=\"Edit\" method=\"POST\">\n" +
"                <strong><font color=\"red\">Cập nhật điểm YFF &nbsp</font></strong> 	\n" +
"                <select name=\"week\" onchange=\"this.form.submit()\">\n");
        for (int i = 0; i < nTours; i++)
        {
            int value = i + 1;
            if (value == selIndex)
                out.println("                                    <option value=\"" + value + "\" selected>Tuần " + value + "</option>\n");
            else
                out.println("                                    <option value=\"" + value + "\">Tuần " + value + "</option>\n");
        }
        out.println(
"                </select>\n" +
"                <br />\n" +
"            </form>");
    }
    private void printFormUpdateTeams(PrintWriter out, Utils myUtil, int week)
    {
        out.println("<form action=\"Edit\" method=\"POST\">\n");
        out.println("<style type=\"text/css\">\n" +
                    "table.tftable {font-size:12px;color:#333333;width:100%;border-width: 1px;border-color: #729ea5;border-collapse: collapse;}\n" +
                    "table.tftable th {font-size:12px;background-color:#acc8cc;border-width: 1px;padding: 8px;border-style: solid;border-color: #729ea5;text-align:left;}\n" +
                    "table.tftable tr {background-color:#d4e3e5;}\n" +
                    "table.tftable td {font-size:12px;border-width: 1px;padding: 8px;border-style: solid;border-color: #729ea5;}\n" +
                    "</style>\n" +
                    "\n" +
                    "<table id=\"tfhover\" class=\"tftable\" border=\"1\">\n" +
                    "<tr><th>Team</th><th>YFF score</th></tr>\n");
        
//                    "<tr><td>Row:1 Cell:1</td><td>Row:1 Cell:2</td></tr>\n" +
        Iterator it = myUtil.yffscores.entrySet().iterator();
        
        int i = 0;
        while (it.hasNext())
        {
            i++;
            Map.Entry pairs = (Map.Entry)it.next();
            String team = (String) pairs.getKey();            
            String[] scores = (String[]) pairs.getValue();
            teaminput.put(team, i);
            out.println("<tr><td>" + team + "</td><td><input type=\"text\" name=\"" + i + "\" value=\"" + scores[week-1] + "\"></td></tr>\n");
        }
        
        out.println("</table>\n");
        out.println("<input type=\"hidden\" name=\"selweek\" value=\"" + week + "\">");
        out.println("<input type=\"submit\" value=\"Save\" onclick=\"showalert()\">");
        out.println("<script>\n" +
                    "function showalert()\n" +
                    "{\n" +
                    "alert(\"Cập nhật điểm thành công!\");\n" +
                    "}\n" +
                    "</script>");
        out.println("</form>\n");
    }
}
